package com.gtlab1207.br_security.services;

import com.gtlab1207.br_security.models.dao.CertDao;
import com.gtlab1207.br_security.models.domain.Cert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.gtlab1207.br_security.common.Util.delFolder;

@Slf4j
@Service
public class DeleteCertService {


    @Autowired
    private CertDao certDao;
    // 证书的基本路径
    String baseCertPath="/Users/shier/Documents/cert/rsa/";
    /**
     * 证书删除层 用于删除失效或不需要的证书
     * @param certpath  证书存储的基础路径
     * @return          true为删除成功 false为删除失败
     */
    public boolean DeleteCert( String alias, String certpath){

        String filepath = certpath;

        // 把数据库中的数据删除
        certDao.deleteCert(alias);

        // 删除证书文件
        File file = new File(filepath);
        // 当前目录不存在 删除失败！
        if(!file.exists()){
            log.error("{} cert file delete false!",alias);
            return false;
        }
        delFolder(filepath);
        return true;
    }

    public boolean DetectCert(){
        List<Cert> certs = certDao.selectCert();
        for (Cert cert : certs) {
            String alias = cert.getAlias();
            String path = cert.getPath();

            // 查看证书的有效时间
            Date start = cert.getDeadline();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(start);
            calendar.add(Calendar.YEAR, 1);
            Date dead = calendar.getTime();
            Date date = new Date();

            System.out.println(dead);

            if(date.compareTo(dead) > 0){
                // 证书过期 需要进行删除操作
                DeleteCert(alias,baseCertPath + alias);
                certDao.deleteCert(alias);
            }
        }
        return true;
    }
}
